package com.lagou;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author: jie.zhao
 * @create: 2021/05/31 15:14
 */
public class ZookeeperSessionCreate implements Watcher{

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    static {
        try {
            zooKeeper = new ZooKeeper(
                            "localhost:2182",60000 , new ZookeeperSessionCreate());
            countDownLatch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

//    public  void init() throws IOException, InterruptedException {
//        zooKeeper = new ZooKeeper(
//                "localhost:2182",60000 , new com.lagou.ZookeeperSessionCreate());
//
//        countDownLatch.await();
//        System.out.println("建立成功链接");
//
//    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        ZookeeperCreateNode zookeeperCreateNode = new ZookeeperCreateNode();
        ZookeeperSelectNode zookeeperSelectNode = new ZookeeperSelectNode();
        if(watchedEvent.getState()==(Event.KeeperState.SyncConnected)) {
            System.out.println("链接回调");

            try {
                String node = zookeeperCreateNode.createNode(zooKeeper, "127.0.0.1:8899", "/service/provide2");
                System.out.println(node);
//                HashMap<String, String> config = zookeeperSelectNode.getServiceNodeAndData(zooKeeper);
//                System.out.println(config);

//                countDownLatch.countDown();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
//        if(watchedEvent.getType()==(Event.EventType.NodeChildrenChanged)){
//            HashMap<String, String> config = zookeeperSelectNode.getServiceNodeAndData(zooKeeper);
//            System.out.println(config);
//
//        }
    }
}
